<template>
  <div class="content">
    <div class="nav">
      <div class="head">
        <div class="head-item">
            <div class="login-register" v-if="isLoggedIn == false">
                <div class="login" @click="Tap('login')">登录</div>
                <div class="register" @click="Tap('register')">注册</div>
            </div>
            <div class="weclome" @click="OutLogin" v-else>
                {{ ruleForm.user_name }}
            </div>
        </div>
        <div class="head-item" @click="goOrder">我的订单</div>
        <div class="head-item" @click="goCollect">我的收藏</div>
        <div class="head-item head-item-cart" @click="goCart">购物车({{ cartNumber == '' ? 0 : cartNumber }})</div>
      </div>
    </div>
    <el-dialog
      :title="login_register == 'login' ? '登录' : '注册'"
      :visible.sync="getShowLogin"
      :show-close="false"
      width="30%"
      class="Dialog"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item class="form_item" label="账号" prop="user_name">
          <el-input v-model="ruleForm.user_name"></el-input>
        </el-form-item>
        <el-form-item class="form_item" label="密码" prop="password">
          <el-input
            type="password"
            show-password
            v-model="ruleForm.password"
          ></el-input>
        </el-form-item>
        <el-form-item class="form_item">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确定</el-button
          >
          <el-button @click="canCel('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters, mapMutations,mapState} from 'vuex'
export default {
  data() {
    return {
      login_register: "login",
      ruleForm:{
        user_name:'admin2',
        password:'123',
        token:''
      },
      rules:{
        user_name:[
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password:[
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  computed:{
    ...mapState({
      isLoggedIn:state=>state.user.isLoggedIn
    }),
    ...mapGetters(['cartNumber','getShowLogin'])
  },
  created(){
    if(sessionStorage.getItem('userInfo')){
      const userInfo = sessionStorage.getItem('userInfo')
      this.setUser(userInfo)
      if(JSON.parse(userInfo).token){
        this.getCartData()
        this.setLoggedIn(true)
      }else {
        this.setLoggedIn(false)
      }
    }
  },
  methods: {
    ...mapMutations(['setUser','setLoggedIn','initCartData','clearCartData','setShowLogin']),
    // 退出登录
    OutLogin(){
        this.$confirm('确定要退出登录吗？','是否退出登录',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(()=>{
          this.setLoggedIn(false)
          //清除vuex数据
          this.clearCartData()
          sessionStorage.removeItem('userInfo')
          this.$message({
          type: 'success',
          message: '退出登录成功!'
        });
        }).catch(()=>{
            this.$message({
            type: 'info',
            message: '已取消'
          }); 
        })
    },
    Tap(type) {
      this.setShowLogin(true)
      if (type == "login") {
        this.login_register = "login";
      } else if (type == "register") {
        this.login_register = "register";
      }
    },
    submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.login_register == 'login'){
                const {user_name,password} = this.ruleForm
                this.Login(user_name,password)
            }else{
              this.Resigter()
            }
          } else {
            this.$notify({
            title: '失败',
            message: '注册失败,请重新注册',
          });
          }
        });
    },
      async Resigter(){
        const res = await this.$http.post('/users/register',this.ruleForm)
        if(res.status == 200){
          this.dialogVisible = false
          this.$notify({
            title: '成功',
            message: '注册成功,欢迎光临',
            type: 'success'
          });
          this.Login()
        }
    },
      async Login(user_name,password){
        const res = await this.$http.post('users/login',{user_name,password})
        if(res.status == 200){
          this.setShowLogin(false)
          this.ruleForm.token = res.data.result.token
          sessionStorage.setItem('userInfo',JSON.stringify(this.ruleForm))
          this.setUser(sessionStorage.getItem('userInfo'))
          this.setLoggedIn(true)
          this.getCartData()
          this.$message({
            message:res.data.message,
            type: 'success'
          });
        }
    },
    async getCartData(pageNumber,pageSize){
      const res = await this.$http.post('/carts/getCarts',{pageNumber,pageSize})
      this.initCartData(res.data.result.list)
    },
    canCel(formName) {
      // 重置表单
      this.$refs[formName].resetFields();
      this.setShowLogin(false)
    },
    goCart(){
      if(this.$route.name !== 'cart'){
        this.$router.push('cart')
      }
    },
    goCollect(){
      if(this.$route.name !== 'collect'){
        this.$router.push('collect')
      }
    },
    goOrder(){
      if(this.$route.name !== 'order'){
        this.$router.push('order')
      }
    }
  },
};
</script>

<style scoped>
.nav {
  width: 100%;
  height: 40px;
  background-color: #3d3d3d;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  cursor: pointer;
}
.head {
  display: flex;
  color: #a8a6a6;
  margin-right: 4%;
}
.head-item {
  padding-right: 30px;
}
.head-item:hover {
  color: white;
}
.login-register {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 8px 0 8px;
}
.login {
  color: #a8a6a6;
  text-decoration: none;
}
.login:hover {
  color: #ffffff;
}
.register {
  color: #a8a6a6;
  text-decoration: none;
}
.register:hover {
  color: #ffffff;
}
</style>